package oceanwiki.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import oceanwiki.entity.Category;
import oceanwiki.mapper.CategoryMapper;
import oceanwiki.req.CategoryQueryReq;
import oceanwiki.req.CategorySaveReq;
import oceanwiki.resp.CategoryQueryResp;
import oceanwiki.resp.PageResp;
import oceanwiki.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import oceanwiki.util.CopyUtil;
import oceanwiki.util.SnowFlake;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author XBJ
 * @since 2024-09-07
 */

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

   @Override
    public PageResp<CategoryQueryResp> listByName(CategoryQueryReq req) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(req.getName()), "name", req.getName());

        //创建分页查询参数
        Page<Category> page = new Page<>(req.getPage(), req.getSize());
        page = this.baseMapper.selectPage(page, queryWrapper);
        List<CategoryQueryResp> resps = CopyUtil.copyList(page.getRecords(), CategoryQueryResp.class);

        //创建返回对象
        PageResp<CategoryQueryResp> pageResp = new PageResp<>();
        pageResp.setList(resps);
        pageResp.setTotal(page.getTotal());

        return pageResp;
    }

    @Override
    public void save(CategorySaveReq req) {
        Category e = CopyUtil.copy(req, Category.class);
        if (ObjectUtils.isEmpty(req.getId())) {//新增
            SnowFlake snowFlake = new SnowFlake();
            long id = snowFlake.nextId();
            e.setId(id);
            this.baseMapper.insert(e);
        } else {//更新
            this.baseMapper.updateById(e);
        }
    }

    @Override
    public void delete(Long id) {
        this.baseMapper.deleteById(id);
    }

   @Override
    public List<CategoryQueryResp> all() {

        // 使用sort列进行排序
        List<Category> categories = this.baseMapper.selectList(new QueryWrapper<Category>().orderByAsc("sort"));

        List<CategoryQueryResp> list = CopyUtil.copyList(categories, CategoryQueryResp.class);

        return list;
    }
}
